<?php


namespace App\Customer\Controller;

use App\Facades\UrlCrypt;
use EchoPHP\Facades\Request;

use Exception;
use EchoPHP\Foundation\Exception\HttpException;

/**
 * 通过推荐邮件内链接直接的页面Controller类
 * Class ByRelyController
 * @package App\Customer\Controller
 */
class ByRelyController extends BaseController {

    /**
     * ByRelyController constructor.
     */
    public function __construct() {
        $this->request = Request::instance();
        $this->chkUrlKey();
    }

    public function chkUrlKey() {
        //通过推荐邮件内链接直接打开，检查令牌合法性
        //http://10.100.51.46:8080/feedbackstep1?subid=4&duetime=1570636800&recommendid=1&key=NjhlZDAyNzIxOTBmZTk1MmYxMDliZjM5ZmE0ODJkZGUuMA==
        try {
            $keyVerify = [];
            if ($this->request->query()->has('recommendid')) {
                $keyVerify['recommendid'] = $this->request->query()->get('recommendid');
            }
            if ($this->request->query()->has('subid')) {
                $keyVerify['subid'] = $this->request->query()->get('subid');
            }
            if ($this->request->query()->has('duetime')) {
                $keyVerify['duetime'] = $this->request->query()->get('duetime');
            }

            $keyVerify['token'] = UrlCrypt::generateToken($keyVerify);

            if ($this->request->query()->has('key')) {
                $keyVerify['key'] = $this->request->query()->get('key');
            }

            if ($keyVerify['key'] == $keyVerify['token']) {
                if ($keyVerify['duetime'] >= time()) {
                    return true;
                }
            }
        } catch (Exception $e) {
            throw new HttpException(self::STATUS_TOKEN_EXPIRED, $e->getMessage());
        }
        throw new HttpException(self::STATUS_TOKEN_EXPIRED, $this->getStatusMsg(self::STATUS_TOKEN_EXPIRED));
    }
}